﻿/*
  课程转换工作流程编号更新不同环境需要更改编号信息  wangjihui,394594745@qq.com

  开发环境：
   var WorkFlowId = "235ba9ad-c7b2-4aa9-b1c4-3861f760a1e5";
   var WorkTaskId = "b78c7b56-f05a-4e96-80f2-cb79054d18fc";

  测试环境：
   var WorkFlowId="de25c215-5b29-43c5-a11e-ae3552aca4b1";
   var WorkTaskId="f4dc3144-6016-4679-801d-152bfaa202a7";

 正式环境： 
  var WorkFlowId="2aa6d3fe-d5ff-484d-bfc6-bc9c3abb0974";
  var WorkTaskId="104f5489-979f-4886-9e82-e80ac69c6757"; 
 
*/

//当前开发环境
var WorkFlowId = "235ba9ad-c7b2-4aa9-b1c4-3861f760a1e5";
var WorkTaskId = "b78c7b56-f05a-4e96-80f2-cb79054d18fc";


YAHOO.example.init = function () {
    function onButtonClick(p_oEvent) {
        switch (this.get("id")) {
            case "btnSave":
                Save();
                break;
            case "btnClose":
                Close();
                break;
            case "btnNew1":
                handleAdd();
                break;
            case "btnDelete1":
                 handleDelete();
                break;
            case "btnNew2":
                handleAdd2();
                break;
            case "btnDelete2":
                handleDelete2();
                break;
            default:
                break;
        }
    }

    YAHOO.util.Event.onContentReady("toolbar", function () {
        btnSave = new YAHOO.widget.Button("btnSave");
        btnSave.on("click", onButtonClick);
        btnClose = new YAHOO.widget.Button("btnClose");
        btnClose.on("click", onButtonClick);
//        btnPay = new YAHOO.widget.Button("btnPay");
//        btnPay.on("click", onButtonClick);
//        btnAgree = new YAHOO.widget.Button("btnAgree");
//        btnAgree.on("click", onButtonClick);
//        btnUnAgree = new YAHOO.widget.Button("btnUnAgree");
//        btnUnAgree.on("click", onButtonClick);
    });

    YAHOO.util.Event.onContentReady("con_two_1", function () {
        btnNews1 = new YAHOO.widget.Button("btnNew1");
        btnNews1.on("click", onButtonClick);
        btnDeletes1 = new YAHOO.widget.Button("btnDelete1");
        btnDeletes1.on("click", onButtonClick);
        });

    YAHOO.util.Event.onContentReady("con_two_2", function () {
        btnNews2 = new YAHOO.widget.Button("btnNew2");
        btnNews2.on("click", onButtonClick);
        btnDeletes2 = new YAHOO.widget.Button("btnDelete2");
        btnDeletes2.on("click", onButtonClick);
    });
} ();

//客户选择对应的方法和ID
var _fn, _id;
function ShowDialog(fn, id, src) {
    _fn = fn;
    _id = id;
    document.getElementById("EditUIWindow1").src = src;
    YAHOO.example.container.dialog1.show();
}

var _NameList = "", _CustomerMrgList = "", _DialogState = "";
YAHOO.namespace("example.container");
YAHOO.util.Event.onDOMReady(function () {
    var handleSubmit = function () {
        var editwindow = document.getElementById("EditUIWindow1");
        if (editwindow) {
            editwindow.contentWindow.ChooseInfo();
            if (_id == "btnCustomerID") {
                LoadCustomerData();
            }
        }
        YAHOO.example.container.dialog1.hide();
    };
    var handleCancel = function () {
        this.cancel();
    };
    var handleSuccess = function (o) {
        var response = o.responseText;
        response = response.split("<!")[0];
        document.getElementById("resp").innerHTML = response;
    };
    var handleFailure = function (o) {
        alert("Submission failed: " + o.status);
    };
    YAHOO.example.container.dialog1 = new YAHOO.widget.Dialog("dialog1",
					            { width: "620px",
					                height: "400px",
					                fixedcenter: true,
					                visible: false,
					                draggable: true,
					                close: true,
					                autofillheight: "body",
					                constraintoviewport: true,
					                buttons: [{ text: "确定", handler: handleSubmit, isDefault: true },
								            { text: "取消", handler: handleCancel}]
					            });
    YAHOO.example.container.dialog1.callback = { success: handleSuccess, failure: handleFailure };
    YAHOO.example.container.dialog1.render();
    //拖动大小dialog1
    var resize1 = new YAHOO.util.Resize("dialog1", {
        handles: ["br"],
        autoRatio: false,
        minWidth: 450,
        minHeight: 300,
        status: false
    });
    resize1.on("startResize", function (args) {
        if (this.cfg.getProperty("constraintoviewport")) {
            var D = YAHOO.util.Dom;
            var clientRegion = D.getClientRegion();
            var elRegion = D.getRegion(this.element);
            resize1.set("maxWidth", clientRegion.right - elRegion.left - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
            resize1.set("maxHeight", clientRegion.bottom - elRegion.top - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
        } else {
            resize1.set("maxWidth", null);
            resize1.set("maxHeight", null);
        }

    }, YAHOO.example.container.dialog1, true);
    resize1.on("resize", function (args) {
        var panelHeight = args.height;
        this.cfg.setProperty("height", panelHeight + "px");
    }, YAHOO.example.container.dialog1, true);
});

//选择客户编码显示客户信息
var LoadCustomerData = function () {
    var vCId = "CustomerId='" + vId + "'"; //订单ID
    YAHOO.util.Connect.asyncRequest('GET', "/Extend/AjaxData/JSONList.aspx?r=" + Math.random() + "&type=1&entity=V_CrmCustomerInfoOrder&customCondition=" + vCId + "", //条件 
        {success: function (res) {
            try {
                var str = res.responseText;
                var arr = [];
                var obj = eval(str);
                $("#txtCustomerIDs").val(obj[0].CustomerCode);
                $("#CustomerName").val(obj[0].CustomerName);
                $("#CustomerType").val(obj[0].TypeName);
                $("#PersonId").val(obj[0].PersonName);
                $("#TradeId").val(obj[0].TradeName);
                $("#CreateDate").val(obj[0].CompanyCreateDate);
                $("#CompanyProduct").val(obj[0].CompanyProduct);
                //$("#Address").val(obj[0].State + obj[0].Province + obj[0].City + obj[0].Address);
                $("#AddUserName").val(obj[0].AddUserName);
                $("#SaleadName").val(obj[0].SaleadviserName);
            }
            catch (e) {
            }
            finally {
            }
        }, failure: function () { }
    });
}

//加载订单产品信息
var OrderProductListByCustomerId = "";
var LoadOrderProductListByCustomerId = function (CustomerId, OrderCode) {
     
    var vCId = "CustomerId='" + vId + "' and Code='" + OrderCode + "'"; //客户ID
    YAHOO.util.Connect.asyncRequest('GET', "/Extend/AjaxData/JSONList.aspx?r=" + Math.random() + "&type=1&entity=V_CrmOrderProductList&customCondition=" + vCId + "", //条件 
        {success: function (res) {
            try {
                
                OrderProductListByCustomerId = res.responseText;
            }
            catch (e) {
            }
            finally {
            }
        }, failure: function () { }
    });
}

var format1 = function (elCell, oRecord, oColumn, sData) {
    if (sData == "" || sData == null) {
        elCell.innerHTML = "<input type=\"text\" value=\"\" readonly='readonly' onchange='ChangeEvent1(this);' name='SetTransfromNumber' style='width:95%;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" readonly='readonly' onchange='ChangeEvent1(this);' name='SetTransfromNumber' style='width:95%;'>";
    }
}
//var format2 = function (elCell, oRecord, oColumn, sData) {
//    if (sData == "" || sData == null) {
//        elCell.innerHTML = "<input type=\"text\" value=\"\" readonly='readonly' onchange='ChangeEvent1(this);' name='Rebate1' style='width:95%;'>";
//    } else {
//        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" readonly='readonly' onchange='ChangeEvent1(this);' name='Rebate1' style='width:95%;'>";
//    }
//}
//var format3 = function (elCell, oRecord, oColumn, sData) {
//    if (sData == "" || sData == null) {
//        elCell.innerHTML = "<input type=\"text\" value=\"\" readonly='readonly' onchange='ChangeEvent1(this);' name='AccountReceivable1' style='width:90px;'>";
//    } else {
//        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" readonly='readonly' onchange='ChangeEvent1(this);' name='AccountReceivable1' style='width:90px;'>";
//    }
//}
var format4 = function (elCell, oRecord, oColumn, sData) {
    if (sData == "" || sData == null) {
        elCell.innerHTML = "<input type=\"text\" value=\"\" readonly='readonly' onchange='ChangeEvent1(this);' name='SetTransfromMoney' style='width:95%;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" readonly='readonly' onchange='ChangeEvent1(this);' name='SetTransfromMoney' style='width:95%;'>";
    }
}
//var format5 = function (elCell, oRecord, oColumn, sData) {
//    var str1 = [];
//    var id = "id" + Math.random();
//    str1.push("<option value='00'> </option>");
//    str1.push("<select id='" + id + "' onchange='ChangeEvent1(this);' name='ProductStateName1' style='width:95%;'>");
//    str1.push("<option value='00'> </option>");
//    for (var i = 0; i < CrmState.length; i++) {
//        //debugger
//        //加载结案|待交付|交付中
//        if (CrmState[i].PhraseID.toLowerCase() == "bddcaf31-98d4-423a-9275-9288f85e2847" ||
//            CrmState[i].PhraseID.toLowerCase() == "af73673f-9fec-4d14-acfd-b0fce08d6ffa" || 
//            CrmState[i].PhraseID.toLowerCase() == "eda4faa9-8544-494c-bf1c-02662e1078a6") {
//            if (CrmState[i].PhraseID == sData) {
//                str1.push("<option value='" + CrmState[i].PhraseID + "' selected>" + CrmState[i].PhraseText + "</option>");
//            } else {
//                str1.push("<option value='" + CrmState[i].PhraseID + "'>" + CrmState[i].PhraseText + "</option>");
//            }
//        }
//    }
//    str1.push("</select>");
//    elCell.innerHTML = str1.join("");
//}

var formatCode = function (elCell, oRecord, oColumn, sData) {
    var str1 = [];
    var id = "id" + Math.random();

    str1.push("<option value='00'> </option>");
    str1.push("<select id='" + id + "' onchange='ChangeEvent1(this);' name='Code' style='width:95%;'>");
    str1.push("<option value='00'> </option>");

    for (var i = 0; i < CrmOrder.length; i++) {
        if (CrmOrder[i].Code == sData) {
            str1.push("<option value='" + CrmOrder[i].ID + "' selected>" + CrmOrder[i].Code + "</option>");
        } else {
            if (CrmOrder.length > 2) {
                if (i > 0) {
                    if (CrmOrder[i].Code != CrmOrder[i - 1].Code) {
                        str1.push("<option value='" + CrmOrder[i].ID + "'>" + CrmOrder[i].Code + "</option>");
                    }
                } else {
                    str1.push("<option value='" + CrmOrder[i].ID + "'>" + CrmOrder[i].Code + "</option>");
                }
            } else {
                str1.push("<option value='" + CrmOrder[i].ID + "'>" + CrmOrder[i].Code + "</option>");
            }
        }
    }
    str1.push("</select>");
    elCell.innerHTML = str1.join("");
}

var formatID = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='ID'>";
}
var formatProductId = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='ProductId'>";
}
var formatOrderProductId = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='OrderProductId'>";
}
var formatProductPackID = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='ProductPackID'>";
}
var formatProductState = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='ProductState'>";
}
var formatUnitId = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='UnitId'>";
}
var formatOrderStateName = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='OrderStateName' style='width:95%; background: #e7eaf4;'>";
}
var formatPackName = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='Packname' style='width:95%; background: #e7eaf4;'>";
}


var vCell, vRecord, vColumn, arrTemp = [];

var formatProName = function (elCell, oRecord, oColumn, sData) {
    vCell = elCell; vRecord = oRecord; vColumn = oColumn;
    var str1 = [];
    var id = "id" + Math.random();
    str1.push("<option value='00'> </option>");
    str1.push("<select id='" + id + "' onchange='ChangeEvent1(this);' name='ProductName' style='width:95%;'>");
    str1.push("<option value='00'> </option>");
    for (var i = 0; i < arrTemp.length; i++) {
        str1.push("<option value='" + arrTemp[i].ProductId + "'>" + arrTemp[i].ProductName + "</option>");
    }
    str1.push("</select>");
    elCell.innerHTML = str1.join("");
}

var formatMoney = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='Money' style='width:95%; background: #e7eaf4;'>";
}
var formatUnitName = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='UnitName' style='width:95%; background: #e7eaf4;'>";
}
var formatAmount = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='Amount' style='width:95%; background: #e7eaf4;'>";
}
var formatRebate = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='Rebate' style='width:95%; background: #e7eaf4;'>";
}
var formatAccountReceivable = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='AccountReceivable' style='width:95%; background: #e7eaf4;'>";
}
var formatResignMoney = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='ResignMoney' style='width:95%; background: #e7eaf4;'>";
}
var formatProductStateName = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='ProductStateName' style='width:95%; background: #e7eaf4;'>";
}

var format6 = function (elCell, oRecord, oColumn, sData) {
    var str1 = [];
    var id = "id" + Math.random();
    str1.push("<option value='00'> </option>");
    str1.push("<select id='" + id + "' onchange='ChangeEvent2(this);' name='Caption' style='width:95%;'>");
    str1.push("<option value='00'> </option>");
    for (var i = 0; i < CrmProduct.length; i++) {
        if (CrmProduct[i].Caption == sData) {
            str1.push("<option value='" + CrmProduct[i].Productid + "' selected>" + CrmProduct[i].Caption + "</option>");
        } else {
            str1.push("<option value='" + CrmProduct[i].Productid + "'>" + CrmProduct[i].Caption + "</option>");
        }
    }
    str1.push("</select>");
    elCell.innerHTML = str1.join("");
}
var format7 = function (elCell, oRecord, oColumn, sData) {
    if (sData == "" || sData == null) {
        elCell.innerHTML = "<input type=\"text\" value=\"\" disabled='disabled' name='Money' style='width:95%; background: #e7eaf4;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='Money' style='width:95%; background: #e7eaf4;'>";
    }
}

var format8 = function (elCell, oRecord, oColumn, sData) {
    var str1 = [];
    var id = "id" + Math.random();
    str1.push("<option value='00'> </option>");
    str1.push("<select id='" + id + "' onchange='ChangeEvent2(this);' name='UnitId' style='width:95%;'>");
    str1.push("<option value='00'> </option>");
    for (var i = 0; i < CrmListUnitId.length; i++) {
        if (CrmListUnitId[i].PhraseID == sData) {
            str1.push("<option value='" + CrmListUnitId[i].PhraseID + "' selected>" + CrmListUnitId[i].PhraseText + "</option>");
        } else {
            str1.push("<option value='" + CrmListUnitId[i].PhraseID + "'>" + CrmListUnitId[i].PhraseText + "</option>");
        }
    }
    str1.push("</select>");
    elCell.innerHTML = str1.join("");
}
var format9 = function (elCell, oRecord, oColumn, sData) {
    if (sData == "" || sData == null) {
        elCell.innerHTML = "<input type=\"text\" value=\"\" name='Amount' readonly='readonly' onchange='ChangeEvent2(this);' style='width:95%;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" name='Amount' readonly='readonly' onchange='ChangeEvent2(this);' style='width:95%;'>";
    }
}
var format10 = function (elCell, oRecord, oColumn, sData) {
    if (sData == "" || sData == null) {
        elCell.innerHTML = "<input type=\"text\" value=\"\" name='Rebate' readonly='readonly' onchange='ChangeEvent2(this);' style='width:95%;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" name='Rebate' readonly='readonly' onchange='ChangeEvent2(this);' style='width:95%;'>";
    }
}
var format11 = function (elCell, oRecord, oColumn, sData) {
    if (sData == "" || sData == null) {
        elCell.innerHTML = "<input type=\"text\" value=\"\" disabled='disabled' name='RebateMoney' style='width:95%; background: #e7eaf4;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='RebateMoney' style='width:95%; background: #e7eaf4;'>";
    }
}
var format12 = function (elCell, oRecord, oColumn, sData) {
    if (sData == "" || sData == null) {
        elCell.innerHTML = "<input type=\"text\" value=\"\" readonly='readonly' name='AccountReceivable' style='width:95%;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" readonly='readonly' onchange='ChangeEvent2(this);' name='AccountReceivable' style='width:95%;'>";
    }
}
var format13 = function (elCell, oRecord, oColumn, sData) {
    if (sData == "" || sData == null) {
        elCell.innerHTML = "<input type=\"text\" value=\"\" name='ResignMoney' readonly='readonly' onchange='ChangeEvent2(this);' style='width:95%;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" name='ResignMoney' readonly='readonly' onchange='ChangeEvent2(this);' style='width:95%;'>";
    }
}
var format14 = function (elCell, oRecord, oColumn, sData) {
    var str1 = [];
    var id = "id" + Math.random();
    str1.push("<option value='00'> </option>");
    str1.push("<select id='" + id + "' disabled='disabled' onchange='ChangeEvent2(this);' name='StateId' style='width:95%;'>");
    for (var i = 0; i < CrmState.length; i++) {
        if (CrmState[i].PhraseID == sData) {
            str1.push("<option value='" + CrmState[i].PhraseID + "' selected>" + CrmState[i].PhraseText + "</option>");
        } else {
            str1.push("<option value='" + CrmState[i].PhraseID + "'>" + CrmState[i].PhraseText + "</option>");
        }
    }
    str1.push("</select>");
    elCell.innerHTML = str1.join("");
}
//var format15 = function (elCell, oRecord, oColumn, sData) {
//    var str1 = [];
//    var id = "id" + Math.random();
//    str1.push("<option value='00'> </option>");
//    str1.push("<select id='" + id + "' onchange='ChangeEvent2(this);' name='Code' style='width:95%;'>");
//    str1.push("<option value='00'> </option>");
//    for (var i = 0; i < CrmOrder.length; i++) {
//        if (CrmOrder[i].Code == sData) {
//            str1.push("<option value='" + CrmOrder[i].ID + "' selected>" + CrmOrder[i].Code + "</option>");
//        } else {
//            if (CrmOrder.length > 2) {
//                if (i > 0) {
//                    if (CrmOrder[i].Code != CrmOrder[i - 1].Code) {
//                        str1.push("<option value='" + CrmOrder[i].ID + "'>" + CrmOrder[i].Code + "</option>");
//                    }
//                } else {
//                    str1.push("<option value='" + CrmOrder[i].ID + "'>" + CrmOrder[i].Code + "</option>");
//                }
//            } else {
//                str1.push("<option value='" + CrmOrder[i].ID + "'>" + CrmOrder[i].Code + "</option>");
//            }
//        }
//    }
//    str1.push("</select>");
//    elCell.innerHTML = str1.join("");
//}
//var formatPayId = function (elCell, oRecord, oColumn, sData) {
//    var str1 = [];
//    var id = "id" + Math.random();
//    str1.push("<option value='00'> </option>");
//    str1.push("<select id='" + id + "' onchange='ChangeEvent2(this);' name='PayId' style='width:98%;'>");
//    str1.push("<option value='00'> </option>");
//    for (var i = 0; i < CrmPayId.length; i++) {
//        if (CrmPayId[i].ID == sData) {
//            str1.push("<option value='" + CrmPayId[i].ID + "' selected>" + CrmPayId[i].Code + "</option>");
//        } else {
//            str1.push("<option value='" + CrmPayId[i].ID + "'>" + CrmPayId[i].Code + "</option>");
//        }
//    }
//    str1.push("</select>");
//    elCell.innerHTML = str1.join("");
//}
var formatPayType = function (elCell, oRecord, oColumn, sData) {
    var str1 = [];
    var id = "id" + Math.random();
    str1.push("<option value='00'> </option>");
    str1.push("<select id='" + id + "' onchange='ChangeEvent2(this);' name='PayType' style='width:98%;'>");
    str1.push("<option value='00'> </option>");
    for (var i = 0; i < CrmPayType.length; i++) {
        if (CrmPayType[i].PhraseText == sData) {
            str1.push("<option value='" + CrmPayType[i].PhraseID + "' selected>" + CrmPayType[i].PhraseText + "</option>");
        } else {
            str1.push("<option value='" + CrmPayType[i].PhraseID + "'>" + CrmPayType[i].PhraseText + "</option>");
        }
    }
    str1.push("</select>");
    elCell.innerHTML = str1.join("");
}
var formatBack = function (elCell, oRecord, oColumn, sData) {
    var str1 = [];
    var id = "id" + Math.random();
    str1.push("<option value='00'> </option>");
    str1.push("<select id='" + id + "' onchange='ChangeEvent2(this);' name='CustomerBank' style='width:98%;'>");
    str1.push("<option value='00'> </option>");
    for (var i = 0; i < CrmPayAccount.length; i++) {
        if (CrmPayAccount[i].PhraseText == sData) {
            str1.push("<option value='" + CrmPayAccount[i].PhraseText + "' selected>" + CrmPayAccount[i].PhraseText + "</option>");
        } else {
            str1.push("<option value='" + CrmPayAccount[i].PhraseText + "'>" + CrmPayAccount[i].PhraseText + "</option>");
        }
    }
    str1.push("</select>");
    elCell.innerHTML = str1.join("");
}
var formatAccount = function (elCell, oRecord, oColumn, sData) {
    if (sData == "" || sData == null) {
        elCell.innerHTML = "<input type=\"text\" value=\"\" readonly='readonly' name='CustomerAccount' style='width:95%;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" readonly='readonly' onchange='ChangeEvent2(this);' name='CustomerAccount' style='width:95%;'>";
    }
}

var formatLimitNumber= function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='LimitNumber' style='width:95%; background: #e7eaf4;'>";
}

var formatLimitMoney= function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='LimitMoney' style='width:95%; background: #e7eaf4;'>";
}

YAHOO.util.Event.addListener(window, "load", function () {
    LoadCustomerData();
    LoadOrderProductListByCustomerId(vId, ordercode);
    BindData();
    BindData1();
    //BindData2();
    hideCol();
});

var BindData = function () {
    YAHOO.example.InlineCellEditing = function () {
        var myColumnDefs1 = [
            { key: "ID", label: "ID", resizeable: true, formatter: formatID }, //订单ID
            {key: "ProductId", label: "ProductId", resizeable: true, formatter: formatProductId },
            { key: "OrderProductId", label: "OrderProductId", resizeable: true, formatter: formatOrderProductId },
            { key: "ProductPackID", label: "ProductPackID", resizeable: true, formatter: formatProductPackID },
            { key: "ProductState", label: "ProductState", resizeable: true, formatter: formatProductState },
            { key: "UnitId", label: "UnitId", resizeable: true, formatter: formatUnitId },
            { key: "Code", label: "订单编码", resizeable: true, width: 130, formatter: formatCode },
            { key: "OrderStateName", label: "订单状态", resizeable: true, width: 80, formatter: formatOrderStateName },
            { key: "Packname", label: "产品包名称", resizeable: true, width: 120, formatter: formatPackName },
            { key: "ProductName", label: "产品名称", resizeable: true, width: 200, formatter: formatProName },
            { key: "Money", label: "单价", resizeable: true, width: 80, formatter: formatMoney },
            { key: "UnitName", label: "单位", resizeable: true, width: 50, formatter: formatUnitName },
            { key: "Amount", label: "数量", resizeable: true, width: 50, formatter: formatAmount },
            { key: "Rebate", label: "折扣率(%)", resizeable: true, formatter: formatRebate },
            { key: "AccountReceivable", label: "应收金额", resizeable: true, formatter: formatAccountReceivable },
            { key: "ResignMoney", label: "已收金额", resizeable: true, formatter: formatResignMoney },
            { key: "ProductStateName", label: "产品状态", resizeable: true, formatter: formatProductStateName },
        //增加列
            { key: "LimitNumber", label: "可转数量", resizeable: true,formatter: formatLimitNumber},
            { key: "LimitMoney", label: "可转金额", resizeable: true, formatter: formatLimitMoney }, 
            { key: "SetTransfromNumber", label: "转出数量", resizeable: true, formatter: format1,
                editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber })
            },
            { key: "SetTransfromMoney", label: "转出金额", resizeable: true, formatter: format4,
                editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber })
            } 
            /*
            { key: "Amount1", label: "修改后数量", resizeable: true, formatter: format1,
                editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber })
            },
            { key: "Rebate1", label: "修改后折扣率(%)", resizeable: true, formatter: format2,
                editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber })
            },
            { key: "AccountReceivable1", label: "修改后应收金额", resizeable: true, formatter: format3,
                editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber })
            },
            { key: "ResignMoney1", label: "修改后已收金额", resizeable: true, formatter: format4,
                editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber })
            },
            { key: "ProductStateName1", label: "修改后产品状态", resizeable: true, formatter: format5 }
            */
            ];

        myDataSource1 = new YAHOO.util.DataSource([{ ID: "", ProductId: "", ProductPackID: "", OrderProductId: "",
            ProductStateId: "", UnitId: "", OrderStateName: "", Packname: "", ProductName: "", Money: "",
            Rebate: "", Amount: "", UnitName: "", AccountReceivable: "", ResignMoney: "", ProductStateName: "",
            LimitNumber:"",LimitMoney:"",SetTransfromNumber:"",SetTransfromMoney:""
        }]);

        myDataSource1.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
        myDataSource1.responseSchema = {
            fields: ["ID", "ProductId", "ProductPackID", "OrderProductId", "ProductStateId", "UnitId", "OrderStateName",
            "Packname", "ProductName", "Money", "Rebate", "Amount", "UnitName", "AccountReceivable", "ResignMoney", "ProductStateName","LimitNumber","LimitMoney","SetTransfromNumber","SetTransfromMoney"
           ] // , "ResignMoney1", "AccountReceivable1", "ProductStateName1", "Amount1", "Rebate1"
        };
        var myDataTable1 = new YAHOO.widget.ScrollingDataTable("con_1", myColumnDefs1,
                            myDataSource1, { width: "99.8%", height: "60px", selectionMode: "single" });
        mDataTable1 = myDataTable1;
        var i1 = 1,
        bReverseSorted1 = false;
        var trackReverseSorts1 = function (oArg) {
            bReverseSorted1 = (oArg.dir === YAHOO.widget.DataTable.CLASS_DESC);
        };
        var onEventSaveCellEditor = function (oArgs) {
            setValue1(oArgs.editor._oColumn.key, oArgs.newData);
        }
        myDataTable1.subscribe("rowMouseoverEvent", myDataTable1.onEventHighlightRow);
        myDataTable1.subscribe("rowMouseoutEvent", myDataTable1.onEventUnhighlightRow);
        myDataTable1.subscribe("rowClickEvent", onEventSelectRow); //myDataTable1.
        myDataTable1.subscribe("cellClickEvent", myDataTable1.onEventShowCellEditor);
        myDataTable1.subscribe("editorSaveEvent", onEventSaveCellEditor);
        myDataTable1.subscribe("checkboxClickEvent", function (oArgs) {
            var elCheckbox = oArgs.target;
            var oRecord = this.getRecord(elCheckbox);
            oRecord.setData("iSun_Selected", elCheckbox.checked);
        });
        return {
            oDS: myDataSource1,
            oDTX: myDataTable1
        };
    } ();
}
var onEventSelectRow = function (oArgs) {
    
    mDataTable1.onEventSelectRow(oArgs);
}

var BindData1 = function () {
    YAHOO.example.InlineCellEditing = function () {
        var myColumnDefs2 = [
            //{ key: "Code", label: "选择订单", resizeable: true, formatter: format15, width: 130 },
            { key: "Caption", label: "产品名称", resizeable: true, formatter: format6, width: 200 },
            { key: "Money", label: "定价", resizeable: true, formatter: format7, width: 80 },
            { key: "UnitId", label: "计量单位", resizeable: true, formatter: format8, width: 80 },
            { key: "Amount", label: "数量", resizeable: true, formatter: format9, width: 50,
                editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber })
            },
            { key: "Rebate", label: "折扣率(%)", resizeable: true, formatter: format10, width: 50,
                editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber })
            },
            { key: "RebateMoney", label: "折扣金额", resizeable: true, formatter: format11, width: 100 },
            { key: "AccountReceivable", label: "应收金额", resizeable: true, formatter: format12, width: 100,
                editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber })
            },
            { key: "ResignMoney", label: "已收金额", resizeable: true, formatter: format13, width: 100,
                editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber })
            },
            { key: "StateId", label: "产品状态", resizeable: true, width: 70, formatter: format14 },
            //{ key: "PayId", label: "缴款单号", resizeable: true, width: 130, formatter: formatPayId },
            { key: "PayType", label: "付款方式", resizeable: true, width: 130, formatter: formatPayType },
            { key: "CustomerBank", label: "到账银行", resizeable: true, width: 200, formatter: formatBack },
            { key: "CustomerAccount", label: "到账银行账号", resizeable: true, width: 130, formatter: formatAccount }
            ];
        myDataSource2 = new YAHOO.util.DataSource([{ Caption: "", Money: "", Rebate: "", Amount: "", UnitId: "",
            RebateMoney: "", AccountReceivable: "", ResignMoney: "", StateId: "",PayId:"",PayType:"",CustomerBank:"",CustomerAccount:""
        }]);
        myDataSource2.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
        myDataSource2.responseSchema = {
            fields: ["Caption", "Money", "Rebate", "Amount", "UnitId", "RebateMoney", "AccountReceivable",
            "ResignMoney", "StateId","PayId", "PayType", "CustomerBank", "CustomerAccount"]
        };
        var myDataTable2 = new YAHOO.widget.ScrollingDataTable("con_2",
            myColumnDefs2, myDataSource2, { width: "99.8%", height: "100%", selectionMode: "single" });
        mDataTable2 = myDataTable2;
        var i2 = 1,
            bReverseSorted1 = false;
        var trackReverseSorts1 = function (oArg) {
            bReverseSorted1 = (oArg.dir === YAHOO.widget.DataTable.CLASS_DESC);
        };
        var onEventSaveCellEditor = function (oArgs) {
            setValue2(oArgs.editor._oColumn.key, oArgs.newData);
        }
        myDataTable2.subscribe("rowMouseoverEvent", myDataTable2.onEventHighlightRow);
        myDataTable2.subscribe("rowMouseoutEvent", myDataTable2.onEventUnhighlightRow);
        myDataTable2.subscribe("rowClickEvent", myDataTable2.onEventSelectRow);
        myDataTable2.subscribe("cellClickEvent", myDataTable2.onEventShowCellEditor);
        myDataTable2.subscribe("editorSaveEvent", onEventSaveCellEditor);
        myDataTable2.subscribe("checkboxClickEvent", function (oArgs) {
            var elCheckbox = oArgs.target;
            var oRecord = this.getRecord(elCheckbox);
            oRecord.setData("iSun_Selected", elCheckbox.checked);
        });
        return {
            ds: myDataSource2,
            dt: myDataTable2
        };
    } ();
}
/*
var BindData2 = function () {
    YAHOO.example.Scrolling = function () {
        var myColumnDefs3 = [
            { key: "Code", label: "订单编码", resizeable: true, width: 130 },
            { key: "Packname", label: "产品包名称", resizeable: true, width: 120 },
            { key: "OldProductName", label: "产品名称", resizeable: true, width: 200 },
            { key: "OldMoney", label: "单价", resizeable: true },
            { key: "NewProductName", label: "修改后产品名称", resizeable: true, width: 200 },
            { key: "NewMoney", label: "产品单价", resizeable: true },
            { key: "OldUnitType", label: "单位", resizeable: true },
            { key: "NewUnitType", label: "修改后单位", resizeable: true },
            { key: "OldAmount", label: "数量", resizeable: true },
            { key: "NewAmount", label: "修改后数量", resizeable: true },
            { key: "OldRebate", label: "折扣率(%)", resizeable: true },
            { key: "NewRebate", label: "修改后折扣率(%)", resizeable: true },
            { key: "OldAccountReceivable", label: "应收金额", resizeable: true },
            { key: "NewAccountReceivable", label: "修改后应收金额", resizeable: true },
            { key: "OldResignMoney", label: "已收金额", resizeable: true },
            { key: "NewResignMoney", label: "修改后已收金额", resizeable: true },
            { key: "AddUserName", label: "修改人", resizeable: true, width: 100 },
            { key: "AddTime", label: "修改时间", resizeable: true, width: 100 }
            ];
        myDataSource3 = new YAHOO.util.DataSource([{ Code: "", Packname: "", OldProductName: "", OldMoney: "", NewProductName: "",
            NewMoney: "", OldUnitType: "", NewUnitType: "", OldAmount: "", NewAmount: "", OldRebate: "",
            NewRebate: "", OldAccountReceivable: "", NewAccountReceivable: "", OldResignMoney: "", NewResignMoney: "",
            AddUserName: "", AddTime: ""
        }]);
        myDataSource3.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
        myDataSource3.responseSchema = {
            fields: ["Code", "Packname", "OldProductName", "OldMoney", "NewProductName",
            "NewMoney", "OldUnitType", "NewUnitType", "OldAmount", "NewAmount", "OldRebate",
            "NewRebate", "OldAccountReceivable", "NewAccountReceivable", "OldResignMoney", "NewResignMoney",
            "AddUserName", "AddTime"]
        };
        var myDataTable3 = new YAHOO.widget.ScrollingDataTable("con_3", myColumnDefs3,
                            myDataSource3, { width: "99.8%", selectionMode: "single" });
        mDataTable3 = myDataTable3;
        var i3 = 1,
        bReverseSorted3 = false;
        var trackReverseSorts3 = function (oArg) {
            bReverseSorted3 = (oArg.dir === YAHOO.widget.DataTable.CLASS_DESC);
        };
        myDataTable3.subscribe("rowMouseoverEvent", myDataTable3.onEventHighlightRow);
        myDataTable3.subscribe("rowMouseoutEvent", myDataTable3.onEventUnhighlightRow);
        myDataTable3.subscribe("rowClickEvent", myDataTable3.onEventSelectRow);
        myDataTable3.subscribe("checkboxClickEvent", function (oArgs) {
            var elCheckbox = oArgs.target;
            var oRecord = this.getRecord(elCheckbox);
            oRecord.setData("iSun_Selected", elCheckbox.checked);
        });
        GetFormValue2();
        return {
            oDS: myDataSource3,
            oDTX: myDataTable3
        };
    } ();
}*/

//隐藏/栏位
function hideCol() {
    mDataTable1.hideColumn(parseInt(0)); mDataTable1.refreshView();
    mDataTable1.hideColumn(parseInt(1)); mDataTable1.refreshView();
    mDataTable1.hideColumn(parseInt(2)); mDataTable1.refreshView();
    mDataTable1.hideColumn(parseInt(3)); mDataTable1.refreshView();
    mDataTable1.hideColumn(parseInt(4)); mDataTable1.refreshView();
    mDataTable1.hideColumn(parseInt(5)); mDataTable1.refreshView();
}

//值改变事件
var ChangeEvent1 = function (oArgs) {
    var f = oArgs.name;
    var v = oArgs.value;
    setValue1(f, v);
}
//f=字段名 v=值
var record;
var setValue1 = function (f, v) {
    //debugger
    var recordID = mDataTable1.getSelectedRows()[0];
    if (recordID != null && recordID.length != 1) {
        record = mDataTable1.getRecord(recordID);
        record._oData[f] = v;
        if (f == "Code") {
            if (v == "00") {
                $($($(".yui-dt-selected")[0]).find("input[name=ID]")[0]).val("");
                record._oData["ID"] = "";
                $($($(".yui-dt-selected")[0]).find("input[name=ProductId]")[0]).val("");
                record._oData["ProductId"] = "";
                $($($(".yui-dt-selected")[0]).find("input[name=OrderProductId]")[0]).val("");
                record._oData["OrderProductId"] = "";
                $($($(".yui-dt-selected")[0]).find("input[name=ProductPackID]")[0]).val("");
                record._oData["ProductPackID"] = "";
                $($($(".yui-dt-selected")[0]).find("input[name=ProductStateId]")[0]).val("");
                record._oData["ProductStateId"] = "";
                $($($(".yui-dt-selected")[0]).find("input[name=UnitId]")[0]).val("");
                record._oData["UnitId"] = "";
                $($($(".yui-dt-selected")[0]).find("input[name=ProductName]")[0]).val("");
                record._oData["ProductName"] = "";
                $($($(".yui-dt-selected")[0]).find("input[name=OrderStateName]")[0]).val("");
                record._oData["OrderStateName"] = "";
                $($($(".yui-dt-selected")[0]).find("input[name=Packname]")[0]).val("");
                record._oData["Packname"] = "";
                $($($(".yui-dt-selected")[0]).find("input[name=Money]")[0]).val("");
                record._oData["Money"] = "";
                
                //                $($($(".yui-dt-selected")[0]).find("input[name=Money1]")[0]).val("");
                //                record._oData["Money1"] = "";
                $($($(".yui-dt-selected")[0]).find("input[name=UnitName]")[0]).val("");
                record._oData["UnitName"] = "";
                $($($(".yui-dt-selected")[0]).find("input[name=Amount]")[0]).val("");
                record._oData["Amount"] = "";
                $($($(".yui-dt-selected")[0]).find("input[name=Rebate]")[0]).val("");
                record._oData["Rebate"] = "";
                $($($(".yui-dt-selected")[0]).find("input[name=AccountReceivable]")[0]).val("");
                record._oData["AccountReceivable"] = "";
                $($($(".yui-dt-selected")[0]).find("input[name=ProductResignMoney]")[0]).val("");
                record._oData["ProductResignMoney"] = "";
                $($($(".yui-dt-selected")[0]).find("input[name=ProductStateName]")[0]).val("");
                record._oData["ProductStateName"] = "";
                arrTemp = "";
                formatProName(vCell, vRecord, vColumn, arrTemp);
                number = 0;

                $("#con_two_2>h3").find("input").each(function () {
                    $(this).val("");
                });
                $("#con_2").css("display", "none");

            } else {
                SetFormValue1(OrderProductListByCustomerId, v); //v:订单ID 
            }
        }

        if (f == "ProductName") {
            var vOrderId = record._oData["ID"];
            setTextValueByName(OrderProductListByCustomerId, v, vOrderId); //v:产品ID

        }

        if (f == "Amount1") {
            if (isNaN(v)) {
                alert("数量必须输入数字!");
                $($($(".yui-dt-selected")[0]).find("input[name=Amount1]")[0]).val("0");
                record._oData["Amount1"] = "0";
            }
            setTextValue();
        }


        if (f == "ResignMoney1") {
            if (isNaN(v)) {
                alert("已收金额必须输入数字!");
                $($($(".yui-dt-selected")[0]).find("input[name=ResignMoney1]")[0]).val("0");
                record._oData["ResignMoney1"] = "0";
            } else {
                var vRM = $($($(".yui-dt-selected")[0]).find("input[name=ResignMoney]")[0]).val();
                if (parseFloat(v) > parseFloat(vRM)) {
                    //alert("输入金额不能大于已收金额!");
                    //$($($(".yui-dt-selected")[0]).find("input[name=ResignMoney1]")[0]).val("0");
                    //record._oData["ResignMoney1"] = "0";
                }
                if (parseFloat(v) == 0) {
                    $($($(".yui-dt-selected")[0]).find("input[name=ResignMoney1]")[0]).val("0");
                    record._oData["ResignMoney1"] = "0";
                }
                var list = mDataTable1.getRecordSet()._records;
                var cValue1 = 0;
                var cValue2 = 0;
                for (var i = 0; i < list.length; i++) {
                    var v1 = parseFloat(list[i]._oData.ResignMoney);
                    cValue1 += v1;
                    var v2 = parseFloat(list[i]._oData.ResignMoney1);
                    cValue2 += v2;
                }
                $('#NewMoney').val(cValue1.toFixed(2) - cValue2.toFixed(2));
            }
        }

        /*
        if (f == "Amount1") {
        if (isNaN(v)) {
        alert("数量必须输入数字!");
        $($($(".yui-dt-selected")[0]).find("input[name=Amount1]")[0]).val("0");
        record._oData["Amount1"] = "0";
        }
        setTextValue();
        }
        if (f == "Rebate1") {
        if (isNaN(v)) {
        alert("折扣率必须输入数字!");
        $($($(".yui-dt-selected")[0]).find("input[name=Rebate1]")[0]).val("100");
        record._oData["Rebate1"] = "100";
        }
        setTextValue();
        }

        if (f == "AccountReceivable1") {
        if (isNaN(v)) {
        alert("应收金额必须输入数字!");
        $($($(".yui-dt-selected")[0]).find("input[name=AccountReceivable1]")[0]).val("0");
        record._oData["ResignMoney1"] = "0";
        }
        setTextValueReceivable();
        }

        if (f == "ResignMoney1") {
        if (isNaN(v)) {
        alert("已收金额必须输入数字!");
        $($($(".yui-dt-selected")[0]).find("input[name=ResignMoney1]")[0]).val("0");
        record._oData["ResignMoney1"] = "0";
        } else {
        var vRM = $($($(".yui-dt-selected")[0]).find("input[name=ResignMoney]")[0]).val();
        if (parseFloat(v) > parseFloat(vRM)) {
        //alert("输入金额不能大于已收金额!");
        //$($($(".yui-dt-selected")[0]).find("input[name=ResignMoney1]")[0]).val("0");
        //record._oData["ResignMoney1"] = "0";
        }
        if (parseFloat(v) == 0) {
        $($($(".yui-dt-selected")[0]).find("input[name=ResignMoney1]")[0]).val("0");
        record._oData["ResignMoney1"] = "0";
        }
        var list = mDataTable1.getRecordSet()._records;
        var cValue1 = 0;
        var cValue2 = 0;
        for (var i = 0; i < list.length; i++) {
        var v1 = parseFloat(list[i]._oData.ResignMoney);
        cValue1 += v1;
        var v2 = parseFloat(list[i]._oData.ResignMoney1);
        cValue2 += v2;
        }
        $('#NewMoney').val(cValue1.toFixed(2) - cValue2.toFixed(2));
        }
           
        } */
    }
}

var SetFormValue1 = function (obj, OrderId) {
    var arr = eval(obj);
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].ID == OrderId) {
            $($($(".yui-dt-selected")[0]).find("input[name=ID]")[0]).val(arr[i].ID);
            record._oData["ID"] = arr[i].ID;
            $($($(".yui-dt-selected")[0]).find("input[name=ProductId]")[0]).val(arr[i].ProductId);
            record._oData["ProductId"] = arr[i].ProductId;
            //$($($(".yui-dt-selected")[0]).find("input[name=OrderProductId]")[0]).val(arr[i].OrderProductId);
            //record._oData["OrderProductId"] = arr[i].OrderProductId;
            $($($(".yui-dt-selected")[0]).find("input[name=ProductPackID]")[0]).val(arr[i].ProductPackID);
            record._oData["ProductPackID"] = arr[i].ProductPackID;
            $($($(".yui-dt-selected")[0]).find("input[name=ProductStateId]")[0]).val(arr[i].ProductStateId);
            record._oData["ProductStateId"] = arr[i].ProductStateId;
            $($($(".yui-dt-selected")[0]).find("input[name=UnitId]")[0]).val(arr[i].UnitId);
            record._oData["UnitId"] = arr[i].UnitId;
            $($($(".yui-dt-selected")[0]).find("input[name=OrderStateName]")[0]).val(arr[i].OrderStateName);
            record._oData["OrderStateName"] = arr[i].OrderStateName;
            $($($(".yui-dt-selected")[0]).find("input[name=Packname]")[0]).val(arr[i].Packname);
            record._oData["Packname"] = arr[i].Packname;
            var arr = [];
            var vArr = eval(OrderProductListByCustomerId);
            for (var j = 0; j < vArr.length; j++) {
                if (OrderId == vArr[j].ID) {
                    var entity = {};
                    var listInfo = mDataTable1.getRecordSet()._records;
                    if (listInfo.length > 1) {
                        for (var m = 1; m < listInfo.length; m++) {
                            //订单状态为结案和交付中
                            if (entity.ProductId != vArr[j].ProductId) {
                                if (vArr[j].ProductStateId.toLowerCase() == "bddcaf31-98d4-423a-9275-9288f85e2847" ||
                                    vArr[j].ProductStateId.toLowerCase() == "eda4faa9-8544-494c-bf1c-02662e1078a6") {
                                    entity.ProductId = vArr[j].ProductId;
                                    entity.ProductName = vArr[j].ProductName;
                                    arr.push(entity);
                                } else {
                                    entity.ProductId = vArr[j].ProductId;
                                    entity.ProductName = vArr[j].ProductName;
                                    arr.push(entity);
                                }
                            }
                        }
                    } else {
                        var entity = {};
                        //订单状态为结案和交付中
                        if (vArr[j].ProductStateId.toLowerCase() == "bddcaf31-98d4-423a-9275-9288f85e2847" ||
                            vArr[j].ProductStateId.toLowerCase() == "eda4faa9-8544-494c-bf1c-02662e1078a6") {
                            entity.ProductId = vArr[j].ProductId;
                            entity.ProductName = vArr[j].ProductName;
                            arr.push(entity);
                        } else {
                            entity.ProductId = vArr[j].ProductId;
                            entity.ProductName = vArr[j].ProductName;
                            arr.push(entity);
                        }
                    }
                }
            }
            arrTemp = arr;
            formatProName(vCell, vRecord, vColumn, arrTemp);
            number++;
        } else {
            $($($(".yui-dt-selected")[0]).find("input[name=Money]")[0]).val("");
            record._oData["Money"] = "";
            $($($(".yui-dt-selected")[0]).find("input[name=UnitName]")[0]).val("");
            record._oData["UnitName"] = "";
            $($($(".yui-dt-selected")[0]).find("input[name=Amount]")[0]).val("");
            record._oData["Amount"] = "";
            $($($(".yui-dt-selected")[0]).find("input[name=Rebate]")[0]).val("");
            record._oData["Rebate"] = "";
            $($($(".yui-dt-selected")[0]).find("input[name=AccountReceivable]")[0]).val("");
            record._oData["AccountReceivable"] = "";
            $($($(".yui-dt-selected")[0]).find("input[name=ResignMoney]")[0]).val("");
            record._oData["ResignMoney"] = "";
            $($($(".yui-dt-selected")[0]).find("input[name=ProductStateName]")[0]).val("");
            record._oData["ProductStateName"] = "";
        }
    }
}
//旧产品列表选择产品，事件处理
var setTextValueByName = function (obj, ProductId, vOrderId) {
    var temp1 = 0;
    if (ProductId == "00") {
        $($($(".yui-dt-selected")[0]).find("input[name=Money]")[0]).val("");
        record._oData["Money"] = "";
        $($($(".yui-dt-selected")[0]).find("input[name=UnitName]")[0]).val("");
        record._oData["UnitName"] = "";
        $($($(".yui-dt-selected")[0]).find("input[name=Amount]")[0]).val("");
        record._oData["Amount"] = "";
        $($($(".yui-dt-selected")[0]).find("input[name=Rebate]")[0]).val("");
        record._oData["Rebate"] = "";
        $($($(".yui-dt-selected")[0]).find("input[name=AccountReceivable]")[0]).val("");
        record._oData["AccountReceivable"] = "";
        $($($(".yui-dt-selected")[0]).find("input[name=ResignMoney]")[0]).val("");
        record._oData["ResignMoney"] = "";
        $($($(".yui-dt-selected")[0]).find("input[name=ProductStateName]")[0]).val("");
        record._oData["ProductStateName"] = "";

        $("#con_two_2>h3").find("input").each(function () {
            $(this).val("");
        });
        $("#con_2").css("display", "none");

    } else {
        //var list = mDataTable1.getRecordSet()._records;
        /* 不存在多条记录
        for (var i = 1; i < list.length; i++) {
        var vProductIdTable = list[i - 1]._oData.ProductName; //列表产品ID
        var vOrderIdTable = list[i - 1]._oData.ID; //列表订单ID
        if (vProductIdTable == ProductId && vOrderIdTable == vOrderId) {
        temp1 = 1;
        $($($(".yui-dt-selected")[0]).find("input[name=OrderProductId]")[0]).val("");
        record._oData["OrderProductId"] = "";
        $($($(".yui-dt-selected")[0]).find("input[name=Money]")[0]).val("");
        record._oData["Money"] = "";
        $($($(".yui-dt-selected")[0]).find("input[name=UnitName]")[0]).val("");
        record._oData["UnitName"] = "";
        $($($(".yui-dt-selected")[0]).find("input[name=Amount]")[0]).val("");
        record._oData["Amount"] = "";
        $($($(".yui-dt-selected")[0]).find("input[name=Rebate]")[0]).val("");
        record._oData["Rebate"] = "";
        $($($(".yui-dt-selected")[0]).find("input[name=AccountReceivable]")[0]).val("");
        record._oData["AccountReceivable"] = "";
        $($($(".yui-dt-selected")[0]).find("input[name=ResignMoney]")[0]).val("");
        record._oData["ResignMoney"] = "";
        $($($(".yui-dt-selected")[0]).find("input[name=ProductStateName]")[0]).val("");
        record._oData["ProductStateName"] = "";

        formatProName(vCell, vRecord, vColumn, arrTemp);
        alert("该订单产品名称已被选中!");
        break;
        }
        }*/
        //debugger
        var arr = eval(obj);
        if (temp1 == 0) {
            for (var i = 0; i < arr.length; i++) {
                if (arr[i].ProductId == ProductId && arr[i].ID == vOrderId) {

                    var tempOrderProductId = arr[i].OrderProductId;
                    var tempMoney = arr[i].Money;
                    var tempUnitName = arr[i].UnitName;
                    var tempAmount = arr[i].Amount; //产品成交数
                    var tempRebate = arr[i].Rebate;
                    var tempAccountReceivable = arr[i].AccountReceivable;  //产品成交金额
                    var tempRegisnMoney = arr[i].ProductResignMoney;       //产品已收金额 缴款金额
                    var tempStateName = arr[i].ProductStateName;

                    var tempTransOverNum = arr[i].TransferNum; //转出数
                    var tempTransferMoney = arr[i].TransferMoney; //转出金额

                    var _lastRegisnMoney = parseFloat(tempRegisnMoney) - parseFloat(tempTransferMoney); //最后实际回款金额
                    // var _lastAmount = parseFloat(tempAmount) - parseFloat(tempTransOverNum); //最后实际成交数

                    //处理产品交付基数大于1的情况。交付了
                    //CrmProduct
                    //var isFlag = isExistProductDeliverBase(CrmProduct, ProductId);
                    // if (isFlag) {
                    var DeliverUrl = "/Extend/AjaxData/CustomOperating.aspx?r=" + Math.random() + "&action=check&entity=CrmMajorStudent&OrderProductId=" + tempOrderProductId;

                    YAHOO.util.Connect.asyncRequest('POST', DeliverUrl, {
                        success: function (res) {
                            try {
                                //debugger
                                var ret = YAHOO.lang.JSON.parse(res.responseText);
                                if (ret.Statue == "Success") {
                                    //没有交付，没有回款。
                                    //                                    if (parseFloat(ret.Msg) == 0 && parseFloat(tempRegisnMoney) == 0) {
                                    //                                        alert("原产品回款为零，且交付为零，不能进行课程转换操作!");
                                    //                                        setItem();
                                    //                                        return;
                                    //                                    }



                                    //是否已经交付完成,剩余转出数量。  ret.Msg= 已经交付的+提交交付单没签到的+转出数量
                                    var _number = parseFloat(tempAmount) - parseFloat(ret.Msg)
                                    if (_number <= 0) {
                                        alert("原产品已经交付完成!");
                                        setItem();
                                        return;
                                    }

                                    //                                    if (parseFloat(tempRegisnMoney) < 0) {
                                    //                                        alert("原产品回款小于零，不能进行课程转换操作!");
                                    //                                        setItem();
                                    //                                        return;
                                    //                                    }

                                    $("#TransfromNumber").val(_number); //剩余交付数量；
                                    $("#DeliverNum").val(ret.Msg); //产品交付数量 


                                    var _Money = (parseFloat(_lastRegisnMoney) <= 0) ? _lastRegisnMoney : _lastRegisnMoney - ((tempAccountReceivable / parseFloat(tempAmount)) * parseFloat(ret.Msg));

                                    var regmoney = /^(\\d+(\\.\\d{2})?)$/;
                                    if (!regmoney.test(_Money)) {
                                        var _tempMoney = _Money.toString();
                                        _Money = _tempMoney.substr(0, _tempMoney.indexOf(".") + 3);
                                    }

                                    $("#NewMoney").val(_Money); //剩余金额；

                                    //--------------------------判断价值业绩--------------------------------//
                                    var SaveUrl = "/Extend/AjaxData/CustomOperating.aspx?r=" + Math.random() + "&action=check&entity=CrmValueCount&OrderProductId=" + tempOrderProductId;
                                    YAHOO.util.Connect.asyncRequest('POST', SaveUrl, {
                                        success: function (res) {
                                            try {
                                                //debugger
                                                var str = res.responseText;
                                                if (str == "0") {
                                                    alert("该订单产品已有价值业绩,请先处理价值业绩后再转换课程!");
                                                    setItem();
                                                    return;
                                                } else {
                                                    $($($(".yui-dt-selected")[0]).find("input[name=OrderProductId]")[0]).val(tempOrderProductId);
                                                    record._oData["OrderProductId"] = tempOrderProductId;
                                                    $($($(".yui-dt-selected")[0]).find("input[name=ProductId]")[0]).val(ProductId);
                                                    record._oData["ProductId"] = ProductId;
                                                    $($($(".yui-dt-selected")[0]).find("input[name=Money]")[0]).val(tempMoney);
                                                    record._oData["Money"] = tempMoney;
                                                    $($($(".yui-dt-selected")[0]).find("input[name=UnitName]")[0]).val(tempUnitName);
                                                    record._oData["UnitName"] = tempUnitName;
                                                    $($($(".yui-dt-selected")[0]).find("input[name=Amount]")[0]).val(tempAmount);
                                                    record._oData["Amount"] = tempAmount;
                                                    $($($(".yui-dt-selected")[0]).find("input[name=Rebate]")[0]).val(tempRebate);
                                                    record._oData["Rebate"] = tempRebate;
                                                    $($($(".yui-dt-selected")[0]).find("input[name=AccountReceivable]")[0]).val(tempAccountReceivable);
                                                    record._oData["AccountReceivable"] = tempAccountReceivable;
                                                    $($($(".yui-dt-selected")[0]).find("input[name=ResignMoney]")[0]).val(tempRegisnMoney);
                                                    record._oData["ResignMoney"] = tempRegisnMoney;
                                                    $($($(".yui-dt-selected")[0]).find("input[name=ProductStateName]")[0]).val(tempStateName);
                                                    record._oData["ProductStateName"] = tempStateName;
                                                    $("#con_2").css("display", "");
                                                }
                                            }
                                            catch (e) {
                                            }
                                            finally {
                                            }
                                        },
                                        failure: function (error) {
                                            alert("数据错误：" + error.statusText);
                                        }
                                    }, null);
                                    //--------------------------判断价值业绩------------------------------// 
                                }
                                else {
                                    alert(ret.Msg);
                                    return;
                                }
                            }
                            catch (e) {
                            }
                            finally {
                            }
                        },
                        failure: function (error) {
                            alert("数据错误：" + error.statusText);
                        }
                    }, null);
                    // } 

                }
            }
        }
        OrderProductListByCustomerId = arr;
    }
}


function setItem() {
    $($($(".yui-dt-selected")[0]).find("input[name=OrderProductId]")[0]).val("");
    record._oData["OrderProductId"] = ""; 
    $($($(".yui-dt-selected")[0]).find("input[name=ProductId]")[0]).val("");
    record._oData["ProductId"] = "00";  
    $($($(".yui-dt-selected")[0]).find("input[name=ProductName]")[0]).val("");
    record._oData["ProductName"] = "00"; 
    $($($(".yui-dt-selected")[0]).find("input[name=Money]")[0]).val("");
    record._oData["Money"] = "";
    $($($(".yui-dt-selected")[0]).find("input[name=UnitName]")[0]).val("");
    record._oData["UnitName"] = "";
    $($($(".yui-dt-selected")[0]).find("input[name=Amount]")[0]).val("");
    record._oData["Amount"] = "";
    $($($(".yui-dt-selected")[0]).find("input[name=Rebate]")[0]).val("");
    record._oData["Rebate"] = "";
    $($($(".yui-dt-selected")[0]).find("input[name=AccountReceivable]")[0]).val("");
    record._oData["AccountReceivable"] = "";
    $($($(".yui-dt-selected")[0]).find("input[name=ResignMoney]")[0]).val("");
    record._oData["ResignMoney"] = "";
    $($($(".yui-dt-selected")[0]).find("input[name=ProductStateName]")[0]).val("");
    record._oData["ProductStateName"] = "";
    //formatProName(vCell, vRecord, vColumn, arr);
    $("#con_2").css("display", "none");
}


//当前产品是否交付基数大于1
function isExistProductDeliverBase(ProductList, ProductID) {
   var flag = false;
   if (!ProductList || ProductList.length == 0) return flag;
   for(var i=0;i<ProductList.length;i++)
   {
       if (ProductList[i].Productid == ProductID) {
           flag = (parseInt(ProductList[i].DeliverCount)> 1);
           break;
       }
   }
   return flag;
}

//formatProName(vCell, vRecord, vColumn, arr);
//alert("该订单产品已有价值业绩,请先处理价值业绩后再转换课程!");
//break;
//var str = 0;
//var SaveUrl = "../../Extend/AjaxData/CustomOperating.aspx?r=" + Math.random() + "&action=check&entity=CrmValueCount&OrderProductId=" + arr[i].OrderProductId;
//YAHOO.util.Connect.asyncRequest('POST', SaveUrl, {
//    success: function (res) {
//        try {
//            str = res.responseText;
//        }
//        catch (e) {
//        }
//        finally {
//        }
//    },
//    failure: function (error) {
//        alert("数据错误：" + error.statusText);
//    }
//}, null);

//剩余金额{}
var setTextValue = function () {
    var vM = record._oData["Money"];
    if (vM == "") {
        alert("请选择产品!");
        return;
    } else {
        var vMoney = parseFloat(record._oData["Money"]);
        var vAmount = 0;
        var vRebate = 100;
        if (record._oData["Amount1"] != null && record._oData["Amount1"] != "null" && record._oData["Amount1"] != "") {
            vAmount = parseFloat(record._oData["Amount1"]);
        }
        if (record._oData["Rebate1"] != null && record._oData["Rebate1"] != "null" && record._oData["Rebate1"] != "" && record._oData["Rebate1"] != "0") {
            vRebate = record._oData["Rebate1"];
        }
        if (record._oData["Amount1"] == "0") {
            $($($(".yui-dt-selected")[0]).find("input[name=Amount1]")[0]).val("0");
            record._oData["Amount1"] = "0";
            $($($(".yui-dt-selected")[0]).find("input[name=Rebate1]")[0]).val("0");
            record._oData["Rebate1"] = "0";
            var list = mDataTable1.getRecordSet()._records;
            var cValue1 = 0;
            var cValue2 = 0;
            for (var i = 0; i < list.length; i++) {
                var v1 = parseFloat(list[i]._oData.ResignMoney);
                cValue1 += v1;
                if (list[i]._oData.ResignMoney1 == "")
                    list[i]._oData.ResignMoney1 = 0;
                var v2 = parseFloat(list[i]._oData.ResignMoney1);
                cValue2 += v2;
            }
            $('#NewMoney').val(cValue1.toFixed(2) - cValue2.toFixed(2));
        }
        var vRebateMoney = (vMoney * vAmount) - (vMoney * vAmount * (vRebate / 100));
        var vAccountReceivable = (vMoney * vAmount) - vRebateMoney;
        $($($(".yui-dt-selected")[0]).find("input[name=RebateMoney1]")[0]).val(vRebateMoney.toFixed(2));
        record._oData["RebateMoney1"] = "" + vRebateMoney.toFixed(2) + "";
        $($($(".yui-dt-selected")[0]).find("input[name=AccountReceivable1]")[0]).val(vAccountReceivable.toFixed(2));
        record._oData["AccountReceivable1"] = "" + vAccountReceivable.toFixed(2) + "";
    }
}
var setTextValueReceivable = function () {
    var vM = record._oData["Money"];
    if (vM == "") {
        alert("请选择产品!");
        return;
    } else {
        var vMoney = record._oData["Money"];
        var vAmount = 1;
        var vRebate = 100;
        if (record._oData["Amount1"] != "") {
            vAmount = record._oData["Amount1"];
        } else {
            alert("请输入数量!");
            return;
        }
        if (record._oData["Rebate1"] != "") {
            vRebate = record._oData["Rebate1"];
        }
        if (vAmount == "0") {
            $($($(".yui-dt-selected")[0]).find("input[name=Rebate1]")[0]).val("0");
            record._oData["Rebate1"] = "0";
        }
        if (record._oData["AccountReceivable1"] == "" || record._oData["AccountReceivable1"] == "0") {
            $($($(".yui-dt-selected")[0]).find("input[name=AccountReceivable1]")[0]).val("0");
            record._oData["AccountReceivable1"] = "0";
            $($($(".yui-dt-selected")[0]).find("input[name=Amount1]")[0]).val("0");
            record._oData["Amount1"] = "0";
            $($($(".yui-dt-selected")[0]).find("input[name=Rebate1]")[0]).val("100");
            record._oData["Rebate1"] = "100";
        } else {
            var AccountReceivable = record._oData["AccountReceivable1"];
            vRebate = (AccountReceivable / (vMoney * vAmount)) * 100;
            $($($(".yui-dt-selected")[0]).find("input[name=Rebate1]")[0]).val(vRebate.toFixed(2));
            record._oData["Rebate1"] = "" + vRebate.toFixed(2) + "";
            var vRebateMoney = (vMoney * vAmount) - (vMoney * vAmount * (vRebate / 100));
            $($($(".yui-dt-selected")[0]).find("input[name=RebateMoney1]")[0]).val(vRebateMoney.toFixed(2));
            record._oData["RebateMoney1"] = "" + vRebateMoney.toFixed(2) + "";
        }
    }
}

//值改变事件
var ChangeEvent2 = function (oArgs) {
    var f = oArgs.name;
    var v = oArgs.value;
    if ((f == "Caption") &&(!CompareDeliver() || !CompareOutMoney())) {
        oArgs.value = "00"; 
        return;
    }
    setValue2(f, v, oArgs);
}
//f=字段名 v=值
var record;
var setValue2 = function (f, v,obj) {
     //debugger;
    var recordID = mDataTable2.getSelectedRows()[0];
    var vIndex = $(".yui-dt-selected").length;
    if (recordID != null && recordID.length != 1) {
        record = mDataTable2.getRecord(recordID);
        record._oData[f] = v;
        if (f == "Caption") {

            //比较两个转换产品是否相同，或者转换后的产品是否相同
            var oldrecordID = mDataTable1.getSelectedRows()[0];  //第一个列表行  
            var oldlist = mDataTable1.getRecord(oldrecordID);

            if (oldlist._oData["ProductId"] == "" || oldlist._oData["ProductId"] == "00") {
                alert("请选择原产品！");
                obj.value = "00";
                record._oData["Caption"] = "00";
                return;
            } 

            if (oldlist._oData["ProductId"] == v) {
                alert("原产品与新产品相同！");
                obj.value = "00";
                record._oData["Caption"] = "00";
                return;
            } 
            

            var list = mDataTable2.getRecordSet()._records; 
            var isexistsmae = false;
            if (list.length > 1) {
                for (var i = 0; i < list.length; i++) {
                    var _productid = list[i]._oData["Caption"];
                    for (var j = i + 1; j < list.length; j++) {
                        if (list[j]._oData["Caption"] == _productid) {
                            isexistsmae = true;
                            break;
                        }
                    }
                }
                if (isexistsmae) {
                    alert("新产品列表中存在相同产品！");
                    obj.value = "00";
                    record._oData["Caption"] = "00";
                    return;
                }
            }

            for (var i = 0; i < CrmProduct.length; i++) {
                if (CrmProduct[i].Productid == v) {
                    $($($(".yui-dt-selected")[vIndex - 1]).find("input[name=Money]")[0]).val(CrmProduct[i].Money);
                    record._oData["Money"] = CrmProduct[i].Money;
                    break;
                }
            } 
            setTextValue2(vIndex);
        }
        if (f == "Amount") {
            if (isNaN(v) || v == "0") {
                alert("数量必须输入数字,且不能为0!");
                $($($(".yui-dt-selected")[vIndex - 1]).find("input[name=Amount]")[0]).val("1");
                record._oData["Amount"] = "1";
            }
            setTextValue2(vIndex);
        }
        if (f == "Rebate") {
            if (isNaN(v)) {
                alert("折扣率必须输入数字!");
                $($($(".yui-dt-selected")[vIndex - 1]).find("input[name=Rebate]")[0]).val("");
                record._oData["Rebate"] = "";
            }
            setTextValue2(vIndex);
        }
        if (f == "AccountReceivable") {
            if (isNaN(v)) {
                alert("应收金额必须输入数字!");
                $($($(".yui-dt-selected")[vIndex - 1]).find("input[name=AccountReceivable]")[0]).val("0");
                record._oData["AccountReceivable"] = "0";
            }
            else {
                var _RMoney = record._oData["ResignMoney"];
                if (parseFloat(v) < parseFloat(_RMoney)) {
                    alert("应收金额小于已收金额，请修改已收金额!");
                    return;
                    //$($($(".yui-dt-selected")[0]).find("input[name=AccountReceivable1]")[0]).val("0");
                    //record._oData["ResignMoney1"] = "0";
                }
            }
            setTextValueReceivable2(vIndex);
        }
        if (f == "ResignMoney") {
            if (isNaN(v)) {
                alert("已收金额必须输入数字!");
                $($($(".yui-dt-selected")[vIndex - 1]).find("input[name=ResignMoney]")[0]).val("0");
                record._oData["ResignMoney"] = "0";
            } else {
                //var vNewMoney = $("#NewMoney").val();

                //应收金额与已收金额的比较
                var _RMoney = record._oData["AccountReceivable"];
                if (parseFloat(v) > parseFloat(_RMoney)) {
                    alert("输入已收金额不能大于应收金额!");
                    $($($(".yui-dt-selected")[vIndex - 1]).find("input[name=ResignMoney]")[0]).val("0");
                    record._oData["ResignMoney"] = "0";
                    return;
                }

                $($($(".yui-dt-selected")[vIndex - 1]).find("input[name=ResignMoney]")[0]).val(parseFloat(v));
                record._oData["ResignMoney"] = parseFloat(v);

                //处理所有订单已收金额总和与转出金额比较
                var vNewMoney = $("#OutMoney").val();
                if (vNewMoney == "") vNewMoney = 0;
                var vNewResignMoney = parseFloat(vNewMoney);

                var nList = mDataTable2.getRecordSet()._records;
                if (!nList && nList.length == 0) return;
                var sumMoney = 0.0;
                var _lsumMoney = 0.0;
                for (var k = 0; k < nList.length; k++) {
                    var _getmoney = nList[k]._oData["ResignMoney"];
                    if (k < nList.length - 1) {
                        _lsumMoney += (!isNaN(_getmoney)) ? parseFloat(nList[k]._oData["ResignMoney"]) : 0;
                    }
                    if (!isNaN(_getmoney)) {
                        sumMoney += parseFloat(nList[k]._oData["ResignMoney"]);
                    }
                }
                if (parseFloat(sumMoney) > vNewResignMoney) {
                    alert("所有产品输入已收金额总和不能大于转出金额!");
                    var temp = vNewResignMoney - _lsumMoney;
                    $($($(".yui-dt-selected")[vIndex - 1]).find("input[name=ResignMoney]")[0]).val(temp);
                    record._oData["ResignMoney"] = temp;
                }
            }
        }
        //        if (f == "PayId") {

        //        }
        if (f == "CustomerBank") {
            for (var i = 0; i < CrmPayAccount.length; i++) {
                if (CrmPayAccount[i].PhraseText == v) {
                    $($($(".yui-dt-selected")[vIndex - 1]).find("input[name=CustomerAccount]")[0]).val(CrmPayAccount[i].PhraseValue);
                    record._oData["CustomerAccount"] = CrmPayAccount[i].PhraseValue;
                }
            }
        }
    }
}
var setTextValue2 = function (vCount) {
    var vM = record._oData["Money"];
    if (vM == "") {
        alert("请选择产品!");
        return;
    } else {
        var vMoney = parseFloat(record._oData["Money"]);
        var vAmount = 0;
        var vRebate = 100;
        if (record._oData["Amount"] != null && record._oData["Amount"] != "null" && record._oData["Amount"] != "") {
            vAmount = parseFloat(record._oData["Amount"]);
        } else {
            vAmount = 1;
        }
        if (record._oData["Rebate"] != null && record._oData["Rebate"] != "null" && record._oData["Rebate"] != "") {
            vRebate = record._oData["Rebate"];
        }
        if (vAmount == "0") {
            $($($(".yui-dt-selected")[0]).find("input[name=Rebate]")[0]).val("0");
            record._oData["Rebate"] = "0";
        }
        var vRebateMoney = (vMoney * vAmount) - (vMoney * vAmount * (vRebate / 100));
        var vAccountReceivable = (vMoney * vAmount) - vRebateMoney;
        $($($(".yui-dt-selected")[vCount - 1]).find("input[name=RebateMoney]")[0]).val(vRebateMoney.toFixed(2));
        record._oData["RebateMoney"] = "" + vRebateMoney.toFixed(2) + "";
        $($($(".yui-dt-selected")[vCount - 1]).find("input[name=AccountReceivable]")[0]).val(vAccountReceivable.toFixed(2));
        record._oData["AccountReceivable"] = "" + vAccountReceivable.toFixed(2) + "";
    }
}
var setTextValueReceivable2 = function (vCount) {
    var vM = record._oData["Money"];
    if (vM == "") {
        alert("请选择产品!");
        return;
    } else {
        var vMoney = record._oData["Money"];
        var vAmount = 0;
        var vRebate = 100;
        if (record._oData["Amount"] != "") {
            vAmount = record._oData["Amount"];
        } else {
            alert("请输入数量!");
            return;
        }
        if (record._oData["Rebate"] != "") {
            vRebate = record._oData["Rebate"];
        }
        if (vAmount == "0") {
            $($($(".yui-dt-selected")[0]).find("input[name=Rebate]")[0]).val("0");
            record._oData["Rebate"] = "0";
        }
        if (record._oData["AccountReceivable"] == "" || record._oData["AccountReceivable"] == "0") {
            $($($(".yui-dt-selected")[0]).find("input[name=AccountReceivable]")[0]).val("0");
            record._oData["AccountReceivable"] = "0";
            $($($(".yui-dt-selected")[0]).find("input[name=Amount]")[0]).val("0");
            record._oData["Amount"] = "0";
            $($($(".yui-dt-selected")[vCount - 1]).find("input[name=RebateMoney]")[0]).val("0");
            record._oData["RebateMoney"] = "0";
            $($($(".yui-dt-selected")[0]).find("input[name=Rebate]")[0]).val("0");
            record._oData["Rebate"] = "0";
        } else {
            var AccountReceivable = record._oData["AccountReceivable"];
            vRebate = (AccountReceivable / (vMoney * vAmount)) * 100;
            $($($(".yui-dt-selected")[vCount - 1]).find("input[name=Rebate]")[0]).val(vRebate.toFixed(2));
            record._oData["Rebate"] = "" + vRebate.toFixed(2) + "";
            var vRebateMoney = (vMoney * vAmount) - (vMoney * vAmount * (vRebate / 100));
            $($($(".yui-dt-selected")[vCount - 1]).find("input[name=RebateMoney]")[0]).val(vRebateMoney.toFixed(2));
            record._oData["RebateMoney"] = "" + vRebateMoney.toFixed(2) + "";
        }
        var list = mDataTable1.getRecordSet()._records;
        var cValue = 0;
        for (var i = 0; i < list.length; i++) {
            if (list[i]._oData.AccountReceivable != "") {
                var v = parseFloat(list[i]._oData.AccountReceivable);
                cValue += v;
            }
        }
        $('#TotalMoney').val(cValue.toFixed(2));
    }
}

//加载变更历史记录数据
var GetFormValue2 = function () {
    var vCId = "CustomerId='" + vId + "'"; //订单ID
    YAHOO.util.Connect.asyncRequest('GET', "/Extend/AjaxData/JSONList.aspx?r=" + Math.random() + "&type=1&entity=V_CrmOrderModifyOperator&customCondition=" + vCId + "", //条件 
        {success: function (res) {
            try {
                var str = res.responseText;
                var arr = eval(str);
                for (var i = 0; i < arr.length; i++) {
                    SetFormValue2(arr);
                }
            }
            catch (e) {
            }
            finally {
            }
        }, failure: function () { }
    });
}
var SetFormValue2 = function (obj) {
    var arr = eval(obj);
    myDataSource2.liveData = arr;
    mDataTable2.getDataSource().sendRequest(null, { success: mDataTable2.onDataReturnInitializeTable }, mDataTable2);
}


//新增行
var number = 0;
var handleAdd = function () {
    if (number == 0) {
        alert("请先操作一行记录后新增!");
        return;
    } else {
        mDataTable1.set("sortedBy", null);
        index = mDataTable1.getRecordSet()._records.length;
        var entity = [{ ID: "", ProductId: "", ProductPackID: "", OrderProductId: "",
            ProductStateId: "", UnitId: "", OrderStateName: "", Packname: "", ProductName: "", Money: "", ProductId1: "",
            Money1: "", Rebate: "", Rebate1: "", Amount: "", Amount1: "", UnitName: "", UnitId1: "",
            AccountReceivable: "", AccountReceivable1: "", ResignMoney: "", ResignMoney1: "", ProductStateName: "",
            ProductStateName1: ""
        }];
        var list = mDataTable1.getRecordSet()._records;
        var elist = [];
        for (var i = 0; i < list.length; i++) {
            if (list[i]._oData.Code == "" || list[i]._oData.Code == null) {
                alert("第" + (i + 1) + "行 订单编码不能为空!");
                return;
            }
            if (list[i]._oData.ProductName == "" || list[i]._oData.ProductName == null || list[i]._oData.ProductName == "00") {
                alert("第" + (i + 1) + "行 产品名称不能为空!");
                return;
            }
            if (list[i]._oData.Amount1 == "" || list[i]._oData.Amount1 == null) {
                alert("第" + (i + 1) + "行 数量不能为空!");
                return;
            }
            if (list[i]._oData.Rebate1 == "" || list[i]._oData.Rebate1 == null) {
                list[i]._oData.Rebate1 = "100";
            }
            if (list[i]._oData.AccountReceivable1 == "" || list[i]._oData.AccountReceivable1 == null) {
                list[i]._oData.AccountReceivable1 = "0";
            }
            if (list[i]._oData.ResignMoney1 == "" || list[i]._oData.ResignMoney1 == null) {
                list[i]._oData.ResignMoney1 = "0";
            }
            if (list[i]._oData.ProductStateName1 == "" || list[i]._oData.ProductStateName1 == null || list[i]._oData.ProductStateName1 == "00") {
                list[i]._oData.ProductStateName1 = list[i]._oData.ProductStateId;
            }
            elist.push(list[i]._oData);
            elist[i].OrderID = list[i]._oData.ID;
            elist[i].CustomerId = vId;
        }
        mDataTable1.addRows(entity, index);
        num++;
    }
}
//删除行//剩余金额{}
var handleDelete = function () {
    var recordID = mDataTable1.getSelectedRows()[0];
    if (recordID != null && recordID.length != 1) {
        if (mDataTable1.getRecordSet()._records.length == 1) {
            alert("最后一行不能删除!");
            return;
        } else {
            mDataTable1.deleteRow(recordID);
            var list = mDataTable1.getRecordSet()._records;
            var cValue = 0;
            for (var i = 0; i < list.length; i++) {
                if (list[i]._oData.ResignMoney1 != "") {
                    var v = parseFloat(list[i]._oData.ResignMoney1);
                    cValue += v;
                }
            }
            $('#NewMoney').val(cValue.toFixed(2));
        }
    } else {
        alert("请选中一行后删除！");
    }
}
//新增行
var handleAdd2 = function () {

//    if (!CompareDeliver() || !CompareOutMoney()) {
//        return;
//    } 

    mDataTable2.set("sortedBy", null);
    index = mDataTable2.getRecordSet()._records.length;
    var entity = [{ Code: "", Caption: "", Money: "", Rebate: "", Amount: "", UnitId: "",
        RebateMoney: "", AccountReceivable: "", ResignMoney: "", StateId: "",
        PayId: "", PayType: "", CustomerBank: "", CustomerAccount: ""
    }];
    mDataTable2.addRows(entity, index);
}
//删除行
var handleDelete2 = function () {
    var recordID = mDataTable2.getSelectedRows()[0];
    if (recordID != null && recordID.length != 1) {
        if (mDataTable2.getRecordSet()._records.length == 1) {
            alert("最后一行不能删除!");
            return;
        } else {
            mDataTable2.deleteRow(recordID);
        }
    } else {
        alert("请选中一行后删除！");
    }
}


//保存 //剩余金额{}
var Save = function () {
    //debugger;
    var list = mDataTable1.getRecordSet()._records;
    var newList = mDataTable2.getRecordSet()._records;
    var elist = [];
    var newElist = [];
    instance[0].ProduectList = "";
    instance[0].NewProduectList = "";
    instance[0].EXP1 = "";  //作为转出数据
    var _DeliverNum = $("#DeliverNum").val();
    for (var i = 0; i < list.length; i++) {
        if (list[i]._oData.Code == "" || list[i]._oData.Code == "00" || list[i]._oData.Code == null) {
            alert("第" + (i + 1) + "行 订单编码不能为空!");
            return;
        }
        if (list[i]._oData.ProductName == "" || list[i]._oData.ProductName == null || list[i]._oData.ProductName == "00") {
            alert("第" + (i + 1) + "行 产品名称不能为空!");
            return;
        }
        if (list[i]._oData.ProductId == "" || list[i]._oData.ProductId == null || list[i]._oData.ProductId == "00") {
            alert("第" + (i + 1) + "行 产品编号不能为空!");
            return;
        }

        //判断没有交付，回款金额为0的不能进行转课
        var oldResignMoney = list[i]._oData.ResignMoney;
        if (list[i]._oData.ResignMoney == "" || list[i]._oData.ResignMoney == null || list[i]._oData.ResignMoney == "0") {
            oldResignMoney = 0;
        }

//        if (isNaN(_DeliverNum)) _DeliverNum = 0;
//        if (_DeliverNum == 0 && oldResignMoney == 0) {
//            alert("第" + (i + 1) + "行 产品没有交付，且没有回款，不能进行转换操作!");
//            return;
//        }

        var _Amount = list[i]._oData.Amount; //产品成交数量

        if (list[i]._oData.Amount == "" || list[i]._oData.Amount == null || list[i]._oData.Amount == "0") {
            alert("第" + (i + 1) + "行 产品成交数量为零或无值!");
            return;
        }

        if (parseFloat(_Amount) <= 0) {
            alert("第" + (i + 1) + "行 产品成交数量小于或等于零!");
            return;
        }

        elist.push(list[i]._oData);
        elist[i].OrderID = list[i]._oData.ID;
        elist[i].CustomerId = vId;
    }

    var _TransfromNumber = $("#TransfromNumber").val(); //可转换数量
    var _NewMoney = $("#NewMoney").val(); //可转换金额
    var _OutNumber = $("#OutNumber").val(); //转出数量
    var _OutMoney = $("#OutMoney").val();   //转出金额  


    if (_TransfromNumber == "" || _NewMoney == "" || _OutNumber == "" || _OutMoney == "") {
        alert("可转换数据或转出数据不能为空！");
        return;
    }

    var reg = /^\d+(\.\d{1,2})?$/;
    if (!reg.test(_TransfromNumber) || !reg.test(_NewMoney) || !reg.test(_OutNumber) || !reg.test(_OutMoney)) {
        alert("可转换数据或转出数据错误，只能输入整数或者两位有效小数！");
        return false;
    }

    if (parseFloat(_OutNumber) > parseFloat(_TransfromNumber)) {
        alert("转出数量大于可转数量！");
        return;
    }

    if (parseFloat(_OutMoney) > parseFloat(_NewMoney)) {
        alert("转出金额大于可转金额！");
        return;
    }

    if (parseFloat(_OutNumber) == parseFloat(_TransfromNumber)) {
        if (parseFloat(_OutMoney) < parseFloat(_NewMoney)) {
            alert("数量全部转出，金额必须全部转出！");
            return;
        }
    } 

    var strmoneyjson = "{\"WorkFlowId\":\"" + WorkFlowId + "\",\"WorkTaskId\":\"" + WorkTaskId + "\",\"DeliverNumber\":\"" + _DeliverNum + "\",\"TransfromNumber\":\"" + _TransfromNumber + "\",\"OutNumber\":\"" + _OutNumber + "\",\"TransformMoney\":\"" + _NewMoney + "\",\"OutMoney\":\"" + _OutMoney + "\"}";
    instance[0].EXP1 = escape(strmoneyjson);

    var strjson = "";
    //处理第一列数据信息
    for (var j = 0; j < elist.length; j++) {
        strjson += ((strjson == "") ? "" : ",") + "{\"OrderID\":\"" + elist[j].OrderID + "\",\"CustomerID\":\"" + elist[j].CustomerId + "\",\"ProductPackID\":\"" +
        elist[j].ProductPackID + "\",\"OrderProductId\":\"" + elist[j].OrderProductId + "\",\"Amount\":\"" + elist[j].Amount + "\",\"Rebate\":\"" +
        elist[j].Rebate + "\",\"AccountReceivable\":\"" + elist[j].AccountReceivable + "\",\"ResignMoney\":\"" + elist[j].ResignMoney + "\",\"ProductStateId\":\"" +
        elist[j].ProductStateId + "\"}";

        //        instance[0].ProduectList += "@" + elist[j].CustomerId + "︾" + elist[j].OrderID + "︾" +
        //                                        elist[j].ProductPackID + "︾" + elist[j].OrderProductId + "︾" +
        //                                        elist[j].Amount + "︾" + elist[j].Amount1 + "︾" +
        //                                        elist[j].Rebate + "︾" + elist[j].Rebate1 + "︾" +
        //                                        elist[j].AccountReceivable + "︾" + elist[j].AccountReceivable1 + "︾" +
        //                                        elist[j].ResignMoney + "︾" + elist[j].ResignMoney1 + "︾" +
        //                                        elist[j].ProductStateId + "︾" + elist[j].ProductStateName1 + "︾";
    }
    instance[0].ProduectList = escape(strjson); //escape("[" + strjson + "]");

    var NewTotalResignMoney = 0;
    for (var t = 0; t < newList.length; t++) {
        if (newList[t]._oData.Caption == "" || newList[t]._oData.Caption == null || newList[t]._oData.Caption == "00") {
            alert("第" + (t + 1) + "行 新产品名称不能为空!");
            return;
        }
        if (newList[t]._oData.UnitId == "" || newList[t]._oData.UnitId == null || newList[t]._oData.UnitId == "00") {
            alert("第" + (t + 1) + "行 新单位不能为空!");
            return;
        }

        if (newList[t]._oData.Amount == "" || newList[t]._oData.Amount == null || parseFloat(newList[t]._oData.Amount) <= 0) {
            alert("第" + (t + 1) + "行 新数量为空或小于等于零!");
            return;
        }

        if (newList[t]._oData.AccountReceivable == "" || newList[t]._oData.AccountReceivable == null || parseFloat(newList[t]._oData.AccountReceivable) <= 0) {
            alert("第" + (t + 1) + "行 新应收金额为空或小于等于零!");
            return;
        }

        if (newList[t]._oData.Rebate == "" || newList[t]._oData.Rebate == null) {
            newList[t]._oData.Rebate = "100";
        }

        if (newList[t]._oData.ResignMoney == "" || newList[t]._oData.ResignMoney == null) {
            newList[t]._oData.ResignMoney = "0";
        }

        if (parseFloat(newList[t]._oData.ResignMoney) < 0) {
            alert("第" + (t + 1) + "行 新已收金额小于零!");
            return;
        }

        if (parseFloat(newList[t]._oData.ResignMoney) > parseFloat(newList[t]._oData.AccountReceivable)) {
            alert("第" + (t + 1) + "行 新已收金额大于新应收金额!");
            return;
        }

        if (parseFloat(newList[t]._oData.ResignMoney) > 0) {
            if (newList[t]._oData.PayType == "" || newList[t]._oData.PayType == null || newList[t]._oData.PayType == "00") {
                alert("第" + (t + 1) + "行 新已收金额不为0!  付款方式不能为空!");
                return;
            }
            if (newList[t]._oData.CustomerBank == "" || newList[t]._oData.CustomerBank == null || newList[t]._oData.CustomerBank == "00") {
                alert("第" + (t + 1) + "行 新已收金额不为0!  到账银行不能为空!");
                return;
            }
            if (newList[t]._oData.CustomerAccount == "" || newList[t]._oData.CustomerAccount == null) {
                alert("第" + (t + 1) + "行 新已收金额不为0!  到账银行账号不能为空!");
                return;
            }

        } else {
            newList[t]._oData.PayId = "00000000-0000-0000-0000-000000000000";
            newList[t]._oData.PayType = "00000000-0000-0000-0000-000000000000";
            newList[t]._oData.CustomerBack = "";
            newList[t]._oData.CustomerAccount = "";
        }

        newElist.push(newList[t]._oData);
        //计算新的已收总金额
        var vNew = parseFloat(newList[t]._oData.ResignMoney);
        NewTotalResignMoney += vNew;
    }

    var vNewResignMoney = parseFloat(_OutMoney);
    if (NewTotalResignMoney < vNewResignMoney) {
        alert("您输入的新产品中已收金额总和小于转出金额!");
        return;
    }


    //比较两个转换产品是否相同，或者转换后的产品是否相同
    var oldrecordID = mDataTable1.getSelectedRows()[0];  //第一个列表行  
    var oldlist = mDataTable1.getRecord(oldrecordID);
    var oldeProduct = oldlist._oData["ProductId"];
    var isexistsame = false;
    var isSame = false;
    for (var i = 0; i < newList.length; i++) {
        var _productid = newList[i]._oData["Caption"];
        if (_productid == oldeProduct) {
            isSame = true;
            break;
        }
        for (var j = i + 1; j < newList.length; j++) {
            if (newList[j]._oData["Caption"] == _productid) {
                isexistsame = true;
                break;
            }
        }
    }
    if (isSame) {
        alert("原产品与新产品相同！");
        return;
    }

    if (isexistsame) {
        alert("新产品列表中存在相同产品！");
        return;
    }


    var vNewStateId = "C3DACC37-2463-458F-BC45-14AD8722BA45";  //订单状态
    strjson = ""; //清除之前的数据
    for (var k = 0; k < newElist.length; k++) {
        strjson += ((strjson == "") ? "" : ",") + "{\"ProductID\":\"" + newElist[k].Caption + "\",\"UnitId\":\"" + newElist[k].UnitId + "\",\"Amount\":\"" +
        newElist[k].Amount + "\",\"Rebate\":\"" + newElist[k].Rebate + "\",\"RebateMoney\":\"" + newElist[k].RebateMoney + "\",\"AccountReceivable\":\"" +
        newElist[k].AccountReceivable + "\",\"ResignMoney\":\"" + newElist[k].ResignMoney + "\",\"ProductPrice\":\"" + newElist[k].Money + "\",\"OrderStateId\":\"" + vNewStateId + "\",\"PayId\":\"\",\"PayType\":\"" +
        newElist[k].PayType + "\",\"CustomerBank\":\"" + newElist[k].CustomerBank + "\",\"CustomerAccount\":\"" + newElist[k].CustomerAccount.replace(/(^\s*)|(\s*$)/g, '') + "\"}";

        //        instance[0].NewProduectList += "@" + newElist[k].Code + "︾" + newElist[k].Caption + "︾" +
        //                                         newElist[k].UnitId + "︾" + newElist[k].Amount + "︾" +
        //                                         newElist[k].Rebate + "︾" + newElist[k].RebateMoney + "︾" +
        //                                         newElist[k].AccountReceivable + "︾" + newElist[k].ResignMoney + "︾" +
        //                                         vNewStateId + "︾" +
        //                                         newElist[k].PayId + "︾" + newElist[k].PayType + "︾" +
        //                                         newElist[k].CustomerBank + "︾" + newElist[k].CustomerAccount.replace(/(^\s*)|(\s*$)/g, '') + "︾";
    }
    instance[0].NewProduectList = escape("[" + strjson + "]");

    SaveData();
}

var SaveData = function () {
    if (instance[0].ProduectList != "") {
        if (confirm("确定要转换课程吗?")) {
            var json = $.toJSON(instance[0]).replace(/'/g, "[B]");
            $("#jsonDataContent").val(json);
            $("#btnSave").attr("disabled", true);
            trySave();
        }
    } else {
        alert("无数据修改!");
    }
}
var trySave = function () {
    var formObject = document.getElementById('form2');
    YAHOO.util.Connect.setForm(formObject);
    var cObj = YAHOO.util.Connect.asyncRequest('POST', "/Extend/AjaxData/CustomOperating.aspx?flag=1&action=insert&entity=CrmOrderModifyOperator&optype=TransFormOrderPay", callback);
}
var responseSuccess = function (res) {
    try { 
        var str = res.responseText;
        var ret = YAHOO.lang.JSON.parse(str);
        if (ret.S == "Success") {
            alert(ret.M);
            RefreshDataParent(); //刷新父页面
            Close(); //关闭当前页
        }
        else {
            alert(ret.M);
        }
    } catch (e) {
        alert(str);
    }
    finally {
        $("#btnSave").attr("disabled", false);
    }
};
var callback = {
    success: responseSuccess,
    failure: responseFailure
};

 
//刷新父窗体数据
function RefreshDataParent() {
    if (parent.NeedRefreshPage != null) {
        if (typeof (parent.NeedRefreshPage.LoadData) == "function") {
            parent.NeedRefreshPage.RefreshData();
        }
    }
}



$(function () { 
    $("#OutNumber").bind("blur", CompareDeliver);
    $("#OutMoney").bind("blur", CompareOutMoney); 
});

function CompareDeliver() {
    var _deliverNum = parseFloat($("#TransfromNumber").val()); //交付数量
    var _conNum = parseFloat($("#OutNumber").val()); //转出数量
    if ($("#OutNumber").val() == "") { alert("请输入转出数量！"); return; }  
    var reg = /^\d+(\.\d{1,2})?$/;
    if (!reg.test(_conNum)) {
        $("#OutNumber").val('');
        alert("输入转出数量错误，只能输入整数或者两位有效小数！"); 
        return false;
    }

    if (_deliverNum<1) {
        $("#OutNumber").val('');
        alert("输入可转数量不能小于一！"); 
        return false;
    }

    if (_conNum > _deliverNum) {
        $("#OutNumber").val('');
        alert("输入转出数量大于实际可转出数！"); 
        return false;
    } 
    return true;    
}

function CompareOutMoney() {
    var _limitMoney = parseFloat($("#NewMoney").val()); //剩余金额
    var _conMoney = parseFloat($("#OutMoney").val()); //转出金额/

    var _deliverNum = parseFloat($("#TransfromNumber").val()); //交付数量
    var _conNum = parseFloat($("#OutNumber").val()); //转出数量

    if ($("#OutMoney").val() == "") { alert("请输入转出金额！"); return; }
    if ($("#OutNumber").val() == "") { alert("请输入转出数量！"); return; } 

    var reg = /^\d+(\.\d{1,2})?$/;
    if (!reg.test(_conMoney)) { 
        $("#OutMoney").val('');
        alert("输入转出金额错误，只能输入整数或者两位有效小数！");
        return false;
    }

    if(_conMoney<0)
    {
      $("#OutMoney").val('');
        alert("输入转出金额不能小于零！"); 
        return false;
    }

    if (_limitMoney <=0) {
        if (_conMoney > 0) {
            $("#OutMoney").val('');
            alert("可转金额为小于等于零，转出金额必须为零！");
            return false;
        }
    }
    else { 
        if (_conMoney > _limitMoney) {
            $("#OutMoney").val('');
            alert("输入转出金额大于实际可转出金额！");
            return false;
        }
    }

    if (_deliverNum == _conNum) {
        if (_limitMoney>0 && _conMoney != _limitMoney) {
            $("#OutMoney").val('');
            alert("数量全部转出，金额必须全部转出！");
            return false;
        }

//        if (_limitMoney <0) {
//            $("#OutMoney").val('');
//            alert("数量全部转出，金额必须全部转出！");
//            return false;
//        }
    }
    return true;    
}
